package com.wandian.texas;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import com.wandian.executor.TimerCommand;
import com.wandian.executor.TimerMgr;
import com.wandian.texas.net.SessionManager;
import com.wandian.util.Config;
import com.wandian.util.ConsoleTable;
import com.wandian.util.Log;
import com.wandian.util.PathUtil;

/**
 * @date : 2012-9-24, 17:34:43
 * @author: long
 * @email :108232706
 * @qq.com
 * @description: Test类
 */
public class Test {

	private static ThreadRun accept = new ThreadRun(SessionMgrImp.getInstance());
	public static void main(String[] args) {
		Log.info("server was run");
		try {
			// PropertyConfigurator.configure(Config.getValue("log4j.path"));
			if (args.length <= 0) {
				Log.error("请输入配置文件地址路径...");
				return;
			}
			GameData.CONFIGPATH = PathUtil.getAasolutePath(args[0]);//String.format("%s/%s", System.getProperty("user.dir"),args[0]).replace('\\', '/');
			testSessionMgr();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public static void testBlockingSocket() throws IOException {
		String mycmd;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			mycmd = br.readLine();
			if ("exit".equals(mycmd)) {
				SessionManager.getInstance().stop();
				break;
			} else if ("startup".equals(mycmd)) {
				if (SessionManager.getInstance().isStarted()) {
					Log.info("server is running!");
				} else {
					if (SessionManager.getInstance().start(9000, 3)) {
						SessionManager.getInstance().acceptProcessor();
					}
				}
			} else if ("shutdown".equals(mycmd)) {
				if (!SessionManager.getInstance().isStarted()) {
					Log.info("server isn't startup!");
				} else {
					SessionManager.getInstance().stop();
				}
			} else {
				Log.info("command is invalide!");
			}
		}
		br.close();
		Log.info("system exit");
	}

	public static boolean initComponent(boolean initResult, String componentName)
	{
		if (!initResult)
			Log.error(componentName + "错误");
		else {
			Log.info(componentName + "加载完成");
		}
		return initResult;
	}

	public static void testSessionMgr() throws Throwable {
		// ThreeRun(id){
		// MainProcess(id);
		// Sleep(1);
		// }
		if (!initComponent(Config.initConfig(GameData.CONFIGPATH), "加载配置文件")) {
			Log.error("系统配置文件加载错误，程序退出!");
			return;
		}
		String mycmd;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			mycmd = br.readLine();
			if ("exit".equals(mycmd)) {
				accept.setRun(false);
				SessionMgrImp.getInstance().stop(false);
				break;
			} else if ("startup".equals(mycmd)) {
				if (SessionMgrImp.getInstance().isStarted()) {
					Log.info("server is running!");
				} else {
					try {
						if (SessionMgrImp.getInstance().start()) {
							accept = new ThreadRun(SessionMgrImp.getInstance());
							accept.start();
							accept.setRun(true);
						} else {
							Log.info("start up error");
						}
					} catch (Throwable e) {
						e.printStackTrace();
						Log.info("start up error:" + e);
					}
				}
				// if (!ThreadPool.getInstance().Start(10, 20)) {
				// Log.info("线程池初始化出现问题！");
				// }
			} else if ("shutdown".equals(mycmd)) {
				SessionMgrImp.getInstance().setAccept(false);
				SessionMgrImp.getInstance().setService(false);
				accept.setRun(false);
				accept.interrupt();
				if (!SessionMgrImp.getInstance().isStarted()) {
					Log.info("server isn't startup!");
				} else {
					SessionMgrImp.getInstance().stop(true);
				}
				SessionMgrImp.getInstance().setStarted(false);
				// ThreadPool.getInstance().stop();
			}
			else if ("testthreadpool".equals(mycmd)) {
				testThreadPool();
			}
			else if ("shuttestthreadpool".equals(mycmd)) {
				TimerMgr.shutdownNow();
			}
			else if ("cmdthread".equals(mycmd)) {
				if (ThreadPool.getInstance().isThreadPoolStated()) {
					ThreadPool.getInstance().printThreadPoolStatus();
				} else {
					Log.info("线程池未启动！");
				}
			}
			else if ("current".equals(mycmd)) {
				printThreadPoolCurrentStatus();
			}
			else {
				Log.info("command is invalide!");
			}
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		br.close();
		Log.info("system exit");
	}

	public static void printThreadPoolCurrentStatus() {
		System.out.println("==============Main Thread Current Status=============");
		ConsoleTable t = new ConsoleTable(5, true);
		t.appendRow();
		t.appendColum("序号").appendColum("线程id").appendColum("isInterrupted").appendColum("isAlive").appendColum("isDaemon");
		t.appendRow();
		t.appendColum(1).appendColum(accept.getName()).appendColum(accept.isInterrupted()).appendColum(accept.isAlive()).appendColum(accept.isDaemon());
		t.appendRow();
		t.appendColum(2).appendColum(Thread.currentThread().getName()).appendColum(Thread.currentThread().isInterrupted()).appendColum(Thread.currentThread().isAlive())
				.appendColum(Thread.currentThread().isDaemon());
		Log.info(t.toString());
		SessionMgrImp.getInstance().printThreadPoolCurrentStatus();
		ThreadPool.getInstance().printThreadPoolCurrentStatus();
	}

	private static void testThreadPool() {
		if (TimerMgr.init(10)) {
			for (int i = 0; i < 10; i++) {
				TimerMgr.push(new Runnable() {
					public void run() {
						ThreadPool.getInstance().Push(new TimerCommand());
					}
				}, 1, 1);
			}
		}
		// 10分钟之后停止
		TimerMgr.shutdown(10, TimeUnit.MINUTES);
	}
}
